package templateapi

import (
	"errors"
	ca "iot-base/common/cache/alarm"
	cpt "iot-base/common/cache/picktemplate"
	"iot-base/common/dbconn"
	"iot-base/common/dbobj"
	"iot-base/common/event"
	"iot-base/common/notify"
	"iot-base/common/webapi"
	"strings"

	"github.com/gin-gonic/gin"
)

func clearDisableAlarm(id string, pt dbobj.PickTemplate) {
	ca.SyncAlarmsByTid(id)
	alarms := ca.GetThingAlarms(id)
	for _, alarm := range alarms {
		aid := alarm.AlarmID
		if aid == "offline" {
			continue
		}
		if !(&pt).IsAlarmEnable(aid) {
			alarm.Flag = "END"
			alarm.Checker = "pickTemplate"
			event.ThingAlarmClear(&alarm)
		}
	}
}

func clearWhileTPChanged(pt dbobj.PickTemplate) {
	var devs []dbobj.DevPickTemplate
	dbconn.DBConnection.Where("pick_template_name=?", pt.SName).Find(&devs)
	if len(devs) > 0 {
		for _, dev := range devs {
			clearDisableAlarm(dev.ThingID, pt)
			tid := dev.ThingID
			notify.PubMsg(false, "templateChanged", &tid)
		}
	}
}

func InitPickTemplateAPI(r *gin.RouterGroup) {
	r.GET("/pickTemplate/:name", func(c *gin.Context) {
		name := c.Param("name")
		if strings.ToLower(name) == "all" {
			var picks []dbobj.PickTemplate
			err := dbconn.DBConnection.Find(&picks).Error
			webapi.SendResult(picks, err, c)
		} else {
			dp, isExist := cpt.GetTemplateByName(name)
			var err error
			if !isExist {
				err = errors.New("记录找不到")
			}
			webapi.SendResult(&dp, err, c)
		}
	})

	r.PUT("/pickTemplate", func(c *gin.Context) {
		var pt dbobj.PickTemplate
		c.ShouldBind(&pt)
		if pt.SName != "" {
			cpt.SaveTemplate(pt)
			clearWhileTPChanged(pt)
			webapi.SendOK(c)
		} else {
			webapi.SendError("参数错误", webapi.ParamMissed, c)
		}

	})
	r.PUT("/devPicTemplate/", func(c *gin.Context) {
		var dp dbobj.DevPickTemplate
		c.ShouldBind(&dp)
		if dp.ThingID != "" && dp.PickTemplateName != "" {
			err := cpt.SaveTemplateToThing(dp)
			pt, _ := cpt.GetTemplateByName(dp.PickTemplateName)
			clearDisableAlarm(dp.ThingID, pt)
			webapi.SendResult(&dp, err, c)

		} else {
			webapi.SendError("参数错误", webapi.ParamMissed, c)
		}
	})
	r.GET("/devPicTemplate/:tid", func(c *gin.Context) {
		var tid = c.Param("tid")
		dp, _ := cpt.GetTemplate(tid)
		webapi.SendResult(&dp, nil, c)
	})

}
